package com.ruoyi.common.config.mybatis.method;

import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import java.util.List;

import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

/**
 * @Classname DataRecoverById
 * @Author: sunluquan
 * @Date: 2021/12/23 16:26
 * @Description TODO
 * 恢复删除标记的数据为正常  根据id
 */
public class RecoverById extends AbstractLogicRecoveryMethod {

    @Override
    public MappedStatement reachableInjectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {

        String sql;

        SqlMethod sqlMethod = SqlMethod.RECOVER_BY_ID;

        List<TableFieldInfo> fieldInfos = tableInfo.getFieldList().stream()
                .filter(TableFieldInfo::isWithUpdateFill)
                .collect(toList());
        if (CollectionUtils.isNotEmpty(fieldInfos)) {
            String sqlSet = "SET " + SqlScriptUtils.convertIf(fieldInfos.stream()
                    .map(i -> i.getSqlSet(EMPTY)).collect(joining(EMPTY)), "!@org.apache.ibatis.type.SimpleTypeRegistry@isSimpleType(_parameter.getClass())", true)
                    + tableInfo.getLogicDeleteSql(false, true);
            sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlSet, tableInfo.getKeyColumn(),
                    tableInfo.getKeyProperty(),
                    sqlLogicDeleteWhere(tableInfo));
        } else {
            sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlLogicNotDeleteSet(tableInfo),
                    tableInfo.getKeyColumn(), tableInfo.getKeyProperty(),
                    sqlLogicDeleteWhere(tableInfo));
        }
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
        return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod() , sqlSource);
    }
}
